<template>
  <div class="login-container">
    <div class="login-form">
      <h2>{{ isLogin ? '登录' : '注册' }}</h2>
      <div class="from-p">
        <p>欢迎使用山东中医药大学智能标注平台</p>
      </div>

      <!-- 使用更简洁的表单结构 -->
      <div class="form-content">
        <!-- 邮箱输入框 -->
        <div class="form-group">
          <label for="email">{{ isLogin ? "登录" : "注册" }}邮箱</label>
          <input type="email" id="email" v-model="formState.email" placeholder="请输入登录邮箱" required class="input-field"
            @input="validateForm" autocomplete="email" />
          <p v-if="formErrors.email" class="error-message">{{ formErrors.email }}</p>
        </div>

        <!-- 密码输入框 -->
        <div class="form-group">
          <label for="password">{{ isLogin ? "登录" : "注册" }}密码</label>
          <input type="password" id="password" v-model="formState.password" placeholder="请输入登录密码" required
            class="input-field" @input="validateForm" autocomplete="current-password" />
          <p v-if="formErrors.password" class="error-message">{{ formErrors.password }}</p>
        </div>

        <!-- 快速登录链接 -->
        <div class="quick-login">
          <router-link to="/home">快速登录</router-link>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <button type="button" class="login-button" :disabled="loading || !isFormValid" @click="handleSubmit">
            {{ isLogin ? '登录' : '注册' }}
            <span v-if="loading">...</span>
          </button>

          <button type="button" class="register-button" @click="toggleMode">
            {{ isLogin ? '注册账号' : '返回登录' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from '@/plugins/axios'
import md5 from 'md5'
import { useEditorStore } from '@/store/editor'

const router = useRouter()
const loading = ref(false)
const isLogin = ref(true)
const editorStore = useEditorStore()

// 统一表单状态管理
const formState = reactive({
  email: '',
  password: ''
})

// 表单错误信息
const formErrors = reactive({
  email: '',
  password: ''
})

// 计算表单是否有效
const isFormValid = computed(() => {
  return !formErrors.email && !formErrors.password &&
    formState.email && formState.password
})

// 表单验证
const validateForm = () => {
  // 验证邮箱
  const emailPattern = /^[a-zA-Z0-9._%+-]+@(163\.com|qq\.com)$/
  formErrors.email = emailPattern.test(formState.email) ? '' : '邮箱格式错误，请输入163邮箱或qq邮箱'

  // 验证密码
  const passwordPattern = /^[A-Z].{8,}$/
  formErrors.password = passwordPattern.test(formState.password) ? '' : '密码格式错误，第一个字符是大写字母,总长度至少为9个字符'
}

// 切换登录/注册模式
const toggleMode = () => {
  isLogin.value = !isLogin.value
  // 切换模式时清空表单
  formState.password = ''
  formErrors.email = ''
  formErrors.password = ''
}

// 提交表单
const handleSubmit = async () => {
  if (!isFormValid.value) {
    ElMessage.warning('请修正表单中的错误')
    return
  }

  loading.value = true

  try {
    if (isLogin.value) {
      await loginUser()
    } else {
      await registerUser()
    }
  } catch (error) {
    console.error(isLogin.value ? '登录错误' : '注册错误', error)
  } finally {
    loading.value = false
  }
}

// 登录逻辑
const loginUser = async () => {
  try {
    const response = await axios.post('/sign_in', {
      email: formState.email,
      password: md5(formState.password)
    })
    const data = response.data
    if (data.success) {
      // 等待 token 保存完成
      await editorStore.setUserAuth(data.token, data.email)
      ElMessage.success(data.message)
      // 确保 token 已保存后再跳转
      await router.push({ name: 'ProjectManagement' })
    } else {
      ElMessage.error(data.message)
    }
  } catch (error) {
    ElMessage.error('Login error:', error)
  }
}

// 注册逻辑
const registerUser = async () => {
  try {
    console.log('尝试注册...')
    const response = await axios.post('/sign_up', {
      email: formState.email,
      password: md5(formState.password)
    })
    const data = response.data
    if (data.code === 200) {
      ElMessage.success(data.msg)
      isLogin.value = true
      formState.password = ''
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    ElMessage.error('注册请求失败，请检查网络连接')
    console.error('注册错误详情：', error)
  }
}
</script>

<style scoped>
*,
*:before,
*:after {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.login-container {
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-attachment: fixed;
  /* 可选：固定背景图片 */
  height: 100vh;
  background: url('@/assets/background.jpg') no-repeat center center;
  background-size: 100% 100%;
  background-position: center center;
  background-blend-mode: multiply;

}

.login-form {
  background: rgba(255, 255, 255, 0.9);
  padding: 20px 50px 60px 50px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  width: 400px;
  text-align: center;
}

h2 {
  font-family: 'Arial', sans-serif;
  /* 字体系列 */
  font-size: 40px;
  /* 字体大小 */
  font-weight: bold;
  /* 加粗 */
  color: #333333;
  /* 字体颜色 */
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
  /* 阴影效果 */
  text-decoration: none;
  /* 去掉下划线 */
  transition: color 0.3s ease;
  /* 过渡效果 */
  margin-bottom: 20px;
}

.from-p {
  font-size: 15px;
  /* 设置字体大小 */
  color: #666;
  /* 设置字体颜色 */
  text-align: center;
  /* 设置文本居中对齐 */
  margin-bottom: 40px;
}

.form-group {
  margin-bottom: 25px;
  text-align: left;
}

label {
  display: block;
  margin-bottom: 5px;
  color: #555555;
}

.input-field {
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
  border: 1px solid #cccccc;
  border-radius: 5px;
  transition: border-color 0.3s;
}

.input-field:focus {
  border-color: #4caf50;
  outline: none;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #333333;
}

.login-button {
  width: 100%;
  height: 40px;
  margin-bottom: 10px;
  background-color: #666666;
  color: white;
  font-family: 'Roboto', sans-serif;
  /* 字体系列 */
  font-size: 18px;
  /* 字体大小 */
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
  /* 阴影效果 */
  text-decoration: none;
  /* 去掉下划线 */
  transition: color 0.3s ease;
  border-radius: 20px;
}

.register-button {
  margin-top: 10px;
  background-color: #666666;
  color: white;
  font-family: 'Roboto', sans-serif;
  /* 字体系列 */
  font-size: 18px;
  /* 字体大小 */
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
  /* 阴影效果 */
  text-decoration: none;
  /* 去掉下划线 */
  transition: color 0.3s ease;
  border-radius: 20px;
}

.forgot-password {
  color: #4caf50;
  text-decoration: none;
  float: right;
}

.error-message {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}

.form-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 20px;
}

.quick-login {
  text-align: center;
  margin-bottom: 10px;
}
</style>
